package com.yange.accountbook.utils


import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import com.yange.accountbook.entity.UserInfoEntity
import kotlin.properties.Delegates

/**
 *
 * @function 用户信息保存
 */
object UserDao {


    private const val userTokenExtra = "userTokenExtra"
    private const val userInfoExtra = "userInfoExtra"
    private const val tokenExpiredExtra = "tokenExpiredExtra"

    //token
    var token: String by Delegates.observable(
        MMKV.defaultMMKV().decodeString(
            userTokenExtra,
            ""
        )
    ) { _, old, new ->
        if (old != new) {
            MMKV.defaultMMKV().encode(userTokenExtra, new)
        }
    }
    var info: String by Delegates.observable(
        MMKV.defaultMMKV().decodeString(
            userInfoExtra,
            ""
        )
    ) { _, old, new ->
        if (old != new) {
            MMKV.defaultMMKV().encode(userInfoExtra, new)
        }
    }

    var tokenExpired: String by Delegates.observable(
        MMKV.defaultMMKV().decodeString(
            tokenExpiredExtra,
            "false"
        )
    ) { _, old, new ->
        if (old != new) {
            MMKV.defaultMMKV().encode(tokenExpiredExtra, new)
        }
    }

    fun isTokenExpired() : Boolean {
        return UserDao.tokenExpired == "true"
    }

    fun getUserInfo(): UserInfoEntity{
        return Gson().fromJson(UserDao.info, UserInfoEntity::class.java)
    }


}